package com.contact.util.util.conversion;

import org.apache.commons.beanutils.converters.AbstractConverter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.contact.util.QuickCode;
import com.contact.util.QuickCodeRegistry;
import com.contact.util.StringUtils;

/**
 * This utility plugs into the commons beanutils framework. It's purpose is to convert Jazz enums (that implement
 * QuickCode) from strings
 * 
 */
public class QuickCodeConverter extends AbstractConverter {

    private static final Log LOG = LogFactory.getLog(QuickCodeConverter.class);

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    protected Object convertToType(Class clazz, Object o) throws Throwable {
        String code = (String) o;
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        QuickCode quickCode = QuickCodeRegistry.fromCode(clazz, code);
        if (quickCode == null) {
            String message = String.format("Code %s did not resolve to a valid QuickCode of type %s.", code,
                    clazz.getSimpleName());
            LOG.error(message);
        }
        return quickCode;
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected Object handleMissing(Class c) {
        return null;
    }

    @Override
    protected Class<?> getDefaultType() {
        return QuickCode.class;
    }

}
